import { GetObjectCommand, S3 } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import {ok} from "@/utils/responseUtil";
const s3Client = new S3({
  endpoint: process.env.OSS_EXTERNAL_ENDPOINT,
  region: process.env.OSS_REGION,
  credentials: {
    accessKeyId: process.env.OSS_ACCESS_KEY,
    secretAccessKey: process.env.OSS_ACCESS_SECRET
  },
  forcePathStyle: true,
})
var fs = require("fs");
const bucketName = 'admin' // 不带 Laf 应用 appid

//拼接文件桶名字
function getInternalBucketName() {
  const appid = process.env.APP_ID;
  return `${appid}-${bucketName}`;
}

//上传文件
async function uploadAppFile(key, body, contentType) {
  const bucket = getInternalBucketName();
  const res = await s3Client
      .putObject({
        Bucket: bucket,
        Key: key,
        ContentType: contentType,
        Body: body,
      })
  return res;
}

//获取文件 url
async function getAppFileUrl(key) {
  const bucket = getInternalBucketName();
  const res = await getSignedUrl(s3Client, new GetObjectCommand({
    Bucket: bucket,
    Key: key,
  }));
  return res;
}

export default async function (ctx: FunctionContext) {
  const stats = fs.statSync(ctx.files[0].path);
  // @ts-ignore
  if (stats.size>(process.env.MAX_SIZE*1024*1024)){
    return ok("文件大小超出限制")
  }
  //获取上传文件的对象
  var data = await fs.readFileSync(ctx.files[0].path);
  //限制文件大小

  await uploadAppFile(
      ctx.files[0].filename,
      data,
      ctx.files[0].mimetype
  );
  const fileUrl = await getAppFileUrl(ctx.files[0].filename);
  return fileUrl.split("?")[0];
};
